<template>
  <div>
    <!-- 个人报名 -->
    <athlete-for-individual
      v-if="currentUserType === 'Personal'"
      v-show="!isConfirm"
      ref="refAthleteForIndividual"
      :user-info="userInfo"
      :game-info="gameInfo"
      :dict="dict"
      :required-id-data="requiredIdData"
      :submit-loading="athleteForIndividual.submitLoading"
      @goConfirmEntry="goIndividualConfirmEntry"
      @onPrevStep="onPrevStep"
      @onSubmitIndividualEntry="submitIndividualEntry"
    />

    <!-- 团体报名 -->
    <athlete-for-team
      v-if="currentUserType === 'Delegation'"
      v-show="!isConfirm"
      ref="refAthleteForTeam"
      :user-info="userInfo"
      :game-info="gameInfo"
      :dict="dict"
      :required-id-data="requiredIdData"
      :submit-loading="athleteForTeam.submitLoading"
      :players="modalByChooseAthlete.players"
      @goConfirmEntry="goTeamConfirmEntry"
      @onChooseAthleteForTeam="clickTeamPlayer"
      @onPrevStep="onPrevStep"
      @onSubmitTeamEntry="submitTeamEntry"
    />

    <!-- 确认报名，准备进行下一步 -->
    <athlete-for-confirm
      v-if="isConfirm"
      :game-info="gameInfo"
      :dict="dict"
      :prop-data="confirmPlayerProps"
      :current-user-type="currentUserType"
      :required-id-data="requiredIdData"
      @onDelegationContinue="onDelegationContinue"
      @onContinue="onContinue"
      @onConfirmEntry="confirmEntry"
    />

    <!-- 选择运动员 -->
    <modal-by-choose-athlete
      ref="modalChoosePlayer"
      title="选择参赛运动员"
      :game-info="gameInfo"
      :user-info="userInfo"
      :dict="dict"
      :required-id-data="requiredIdData"
      @onSubmitAthlete="submitChooseAthlete"
    />

    <!-- 添加运动员弹窗 -->
    <van-popup v-model="dialogVisibleForPersonal" get-container="#app" position="right" :style="{ width: '100%', height: '100%' }">
      <div class="add_member">
        <van-nav-bar class="main_header" title="编辑">
          <template #left>
            <span @click="dialogVisibleForPersonal = false">返回</span>
          </template>
          <template #right>
            <span @click="submitPersonalInfo">确定</span>
          </template>
        </van-nav-bar>
        <div class="add_member_content">
          <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :is-default-check="createRegisterInput.isApproved" />
        </div>
      </div>
    </van-popup>

  </div>
</template>

<script>
import {
  api_POST_EventsManagementRegisterWithtags, // 添加会员 多选标签
  api_POST_EventsManagementEntryOrUpdate // 2-添加报项，包含了教练或领队便于一次性提交，单个报项(除操作控制外)
} from '@/extend/api/gameswaggerApi/app';

import {
  Api_GET_EventsManagementEntryByPersonQO, // 表单: 12-查询报项（按个人汇总报项）
  SiSTKWEventsManagementCreateRegisterWithTagsInput,
  SiSTKWEventsManagementCreateEntrysForSingleRegisterInput //  表单: 2-添加报项，包含了教练或领队便于一次性提交，单个报项(除操作控制外)
} from '@/lib/form/game/swaggerForm';

import AthleteForTeam from './athleteForTeam.vue';
import AthleteForIndividual from './athleteForIndividual.vue';
import ModalByChooseAthlete from './modalByChooseAthlete.vue';
import AthleteForConfirm from './athleteForConfirm.vue';

import personalInfo from '@/viewMobile/components/PersonalInfo';

import { CopyData } from '@/lib';

export default {
  components: {
    AthleteForTeam,
    AthleteForIndividual,
    ModalByChooseAthlete,
    AthleteForConfirm,
    personalInfo
  },
  props: {
    // 当前用户的类型 Personal : 个人; Delegation ：团体; PersonalDelegation ：个人 + 团体
    currentUserType: {
      type: String,
      default: ''
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    officialData: {
      type: Array,
      default () {
        return [];
      }
    },
    dict: {
      type: Object,
      default () {
        return {};
      }
    },
    // 字典信息
    district: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data () {
    return {
      isConfirm: false,
      confirmPlayerProps: {},
      athleteForIndividual: {
        submitLoading: false
      },
      athleteForTeam: {
        submitLoading: false
      },
      modalByChooseAthlete: {
        players: []
      },
      dialogVisibleForPersonal: false, // 添加运动员模态框显示隐藏
      submitPersonalInfoLoading: false, // 添加运动员的按钮Loading
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterWithTagsInput() // 添加人员vo
    };
  },
  computed: {
    // 是否是 个人 类型
    isPersonal () {
      return this.currentUserType === 'Personal';
    },
    // 是否是 团体 类型
    isDelegation () {
      return this.currentUserType === 'Delegation';
    },
    // 教练裁判数组
    officialDataList () {
      return this.officialData || [];
    }
  },
  watch: {
    isConfirm(val) {
      if (!val) {
        this.reCheckEntry();
      }

      if (val) {
        this.$emit('onChangeAthletePageType', 'confirm');
      } else {
        this.$emit('onChangeAthletePageType', '');
      }
    },
    dialogVisibleForPersonal(val) {
      if (!val) {
        // this.$refs.refPersonalInfo.clearInsideUserData();
        this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      }
    }
  },
  methods: {
    // 点击上一步
    onPrevStep() {
      this.$emit('onPrevStep');
    },
    // 点击选择参赛运动员（团体）
    clickTeamPlayer () {
      this.$refs.modalChoosePlayer.open();
    },
    // 重新检测项目
    reCheckEntry () {
      if (this.isPersonal) {
        this.$nextTick(() => {
          if (this.$refs.refAthleteForIndividual) {
            this.$refs.refAthleteForIndividual.checkEntry();
          }
        });
      }
    },
    // 确认个人报名
    submitIndividualEntry (data, allEventList) {
      this.athleteForIndividual.submitLoading = true;
      const _vo = new SiSTKWEventsManagementCreateEntrysForSingleRegisterInput();
      _vo.competitionId = data.competitionId;
      _vo.delegationId = data.delegationId;
      _vo.registerId = data.registerId;
      _vo.subCompetitionId = data.entrySubstationId;
      _vo.officials = this.officialDataList;
      _vo.entrys = data.eventIds.map(item => {
        return {
          eventId: item
        };
      });
      this.apiEventEntry(_vo)
        .then(
          res => {
            this.athleteForIndividual.submitLoading = false;
            console.log('submitIndividualEntry -> res', res);
            this.$toast.success(`提交报名成功`);
            this.$refs.refAthleteForIndividual.checkEntry();
          }
        )
        .catch(
          error => {
            this.athleteForIndividual.submitLoading = false;
            this.$toast.fail(`报名失败 ${error.error.message}`);
          }
        );
    },
    // 确认团体报名
    submitTeamEntry (propRegisterId, allEventData) {
      this.athleteForTeam.submitLoading = true;
      const _vo = new SiSTKWEventsManagementCreateEntrysForSingleRegisterInput();
      _vo.competitionId = this.gameInfo.id;
      _vo.delegationId = this.requiredIdData.delegationId;
      _vo.registerId = propRegisterId;
      _vo.officials = this.officialDataList;
      _vo.entrys = allEventData._allEventList;
      _vo.subCompetitionId = allEventData.entrySubstationId;
      this.apiEventEntry(_vo)
        .then(
          res => {
            this.athleteForTeam.submitLoading = false;
            console.log('submitIndividualEntry -> res', res);
            this.$toast.success(`报名成功`);
          }
        )
        .catch(
          error => {
            this.athleteForTeam.submitLoading = false;
            this.$toast.fail(`报名失败 ${error.error.message}`);
          }
        );
    },
    // 报名接口
    apiEventEntry(vo) {
      return new Promise((resolve, reject) => {
        api_POST_EventsManagementEntryOrUpdate(vo)
          .then(
            res => {
              resolve(res);
            }
          )
          .catch(
            error => {
              reject(error);
            }
          );
      });
    },
    // 确认选择运动员
    submitChooseAthlete (list) {
      this.modalByChooseAthlete.players = [list];
      this.$nextTick(() => {
        this.$refs.refAthleteForTeam.resetViewData();
      });
    },
    // 跳转至报项页面
    goIndividualConfirmEntry () {
      this.confirmPlayerProps = new Api_GET_EventsManagementEntryByPersonQO();
      this.confirmPlayerProps.CompetitionId = this.gameInfo.id;
      this.confirmPlayerProps.RegisterId = this.requiredIdData.registerId;
      this.confirmPlayerProps.DelegationId = null;
      this.confirmPlayerProps.CompRegisterApproveStatusCode = 'NotPaid';
      this.confirmPlayerProps.CompEntryApproveStatusCode = null;
      this.isConfirm = true;
    },
    // 跳转至报项页面
    goTeamConfirmEntry () {
      this.confirmPlayerProps = new Api_GET_EventsManagementEntryByPersonQO();
      this.confirmPlayerProps.CompetitionId = this.gameInfo.id;
      this.confirmPlayerProps.RegisterId = null;
      this.confirmPlayerProps.DelegationId = this.requiredIdData.delegationId;
      this.confirmPlayerProps.CompRegisterApproveStatusCode = 'NotPaid';
      this.confirmPlayerProps.CompEntryApproveStatusCode = null;
      this.isConfirm = true;
    },
    // 继续报名
    onContinue () {
      this.isConfirm = false;
    },
    onDelegationContinue (athlete) {
      this.isConfirm = false;
      this.modalByChooseAthlete.players = [athlete];
      this.$nextTick(() => {
        this.$refs.refAthleteForTeam.chooseAthleteAndGetEntry(athlete);
      });
    },
    // 确定报名并进行下一步
    confirmEntry () {
      this.$emit('onNextStep');
    },
    clickAddAthlete () {
      this.dialogVisibleForPersonal = true;
    },
    // 提交个人信息
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            if (res.imagePath) {
              CopyData(res, this.createRegisterInput);
              this.createRegisterInput.registerTypeCode = 'I';
              this.createRegisterInput.registerTags = ['Athlete'];
              this.createRegisterInput.isCurrentUser = false;
              this.createRegisterInput.joinCurrentDelegation = true;
              this.apiRegisterWithTags();
            } else {
              this.$toast({ type: 'fail', message: `请上传头像` });
            }
          }
        );
    },
    apiRegisterWithTags () {
      this.submitPersonalInfoLoading = true;
      api_POST_EventsManagementRegisterWithtags(this.createRegisterInput)
        .then(
          res => {
            this.submitPersonalInfoLoading = false;
            this.$toast.success(`添加成功`);
            this.dialogVisibleForPersonal = false;
          }
        )
        .catch(
          error => {
            this.submitPersonalInfoLoading = false;
            this.$toast.fail(`添加失败 ${error.error.message}`);
          }
        );
    }
  }
};
</script>
